import { dialog } from 'electron';
import common from 'mv-common';

import fs from 'fs';
import path from 'path';
import mimeType from 'mime-types';

import { PRINT_MAX_SIZE } from '../constance';
import PrinterSdk from '../core/PrinterSdk';
import EventBasicRegister from '../core/EventBasicRegister';

interface FileList {
    filename: string;
    url: string;
    type?: string;
}

class Services extends EventBasicRegister {
    supportPrintType: Array<string> = [];
    listenerEventList = [
        { name: 'open:print', handler: this.openPrint.bind(this) },
        { name: 'add:local:task', handler: this.addLocalTask.bind(this) },
        {
            name: 'set:support:print:type',
            handler: this.setSupportPrintType.bind(this)
        }
    ];

    public sendPrintFile(fileList: Array<FileList>) {
        this.sendEvent('print:file', fileList);
    }

    public filterSupportFile(dirPath: string, files: Array<string>) {
        const fileList: Array<FileList> = [];
        for (const item of files) {
            if (fileList.length > PRINT_MAX_SIZE) {
                throw new Error(
                    `单次打印最大支持${PRINT_MAX_SIZE}个文件，请重新选择`
                );
            }
            const filePath = path.join(dirPath, item);
            const fileType = mimeType.lookup(filePath);
            if (fileType && this.supportPrintType.includes(fileType)) {
                fileList.push({
                    filename: path.basename(filePath),
                    url: filePath
                });
            }
        }
        return fileList;
    }

    public async addLocalTask() {
        try {
            const choosePaths = dialog.showOpenDialogSync({
                title: '请选择文件夹, 此文件夹下的浅层文件将被识别打印',
                properties: ['openDirectory', 'promptToCreate']
            });
            if (!choosePaths) throw new Error('未选择文件');
            const chooseDir = choosePaths[0];
            if (!fs.existsSync(chooseDir)) throw new Error('选择的目录不存在');
            const files = common.readForTypeFileDir(chooseDir, 'file');
            if (!files.length) throw new Error('选择的目录为空');
            const supportFileList = this.filterSupportFile(chooseDir, files);
            if (!supportFileList.length)
                throw new Error('选择的目录下，没有可支持的文件打印类型');
            this.sendPrintFile(supportFileList);
        } catch (e) {
            return { message: (e as unknown as { message: string }).message };
        }
    }

    public async openPrint() {
        return PrinterSdk.run();
    }

    public setSupportPrintType(_: unknown, _$: unknown, value: string) {
        this.supportPrintType = JSON.parse(value);
    }
}

export default new Services();
